import subprocess as sub

from django.shortcuts import render
from django.http import HttpResponseNotFound, Http404, HttpResponse
from django.core.exceptions import RequestDataTooBig, PermissionDenied
from django.views.decorators import http
from django.shortcuts import get_object_or_404, get_list_or_404

from .models import Book


def index(request):
    books = get_list_or_404(Book)
    context = {'data': books, 'title': 'Index 1', 'total': 1}
    return render(request, 'app1/index.html', context=context)


def detail(request, pk):
    book = get_object_or_404(Book, pk=pk)
    return render(request, 'app1/detail.html', context=dict(book=book))


def e(request, code):
    code = int(code)
    if code == 400:
        raise RequestDataTooBig()
    elif code == 403:
        raise PermissionDenied()
    elif code == 404:
        raise Http404()
    else:
        raise Exception()


def online_user_list(request):
    out = sub.getoutput('who')
    lines = out.splitlines()
    info = [line.split() for line in lines]
    header = ('name', 'tty', 'date', 'time', 'source')
    info = [dict(zip(header, x)) for x in info]
    return render(request, 'app1/online_user_list.html', context={'users': info})


def online_user_detail(request, name):
    lines = open('/etc/passwd').read().splitlines()
    users = [line.split(':') for line in lines]
    user = [user for user in users if user[0] == name]
    if not user:
        return HttpResponseNotFound('user not found')

    user = user[0]
    header = ('name', 'password', 'uid', 'gid', 'comment', 'home', 'shell')
    user = dict(zip(header, user))

    return render(request, 'app1/online_user_detail.html', context={'user': user})
